package com.csgc.camera.biz.other.activity

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.text.Layout
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import coil.load
import com.csgc.camera.base.BaseBindingActivity
import com.csgc.camera.constants.Constants
import com.csgc.camera.constants.MaskConfig
import com.csgc.camera.events.ChangeCustomMaskStatusEvent
import com.csgc.camera.events.ChangeMaskEvent
import com.csgc.camera.events.CustomMaskEvent
import com.csgc.camera.events.DeleteAlbumEvents
import com.csgc.camera.events.showMaskEditDialogEvent
import com.csgc.camera.util.CommonUtils
import com.csgc.camera.util.FileUtils
import com.csgc.camera.util.GetPathFromUri
import com.csgc.camera.util.ImageUtil
import com.csgc.camera.util.ViewUnit
import com.csgc.camera.util.ViewUtils
import com.csgc.camera.util.WXWrapper
import com.csgc.camera.util.clickWithTrigger
import com.csgc.camera.util.deleteFromAlbum
import com.csgc.camera.util.dp
import com.csgc.camera.util.saveToAlbum
import com.csgc.camera.widget.CoilEngine
import com.csgc.camera.widget.dialog.CommonHandleTipsDialog
import com.csgc.camera.widget.dialog.CustomMaskHandle
import com.csgc.camera.widget.dialog.EditImageDialog
import com.csgc.camera.widget.dialog.EditImageLabelDialog
import com.csgc.camera.widget.dialog.EditImageTxtDialog
import com.csgc.camera.widget.dialog.EditMaskDialog
import com.csgc.camera.widget.dialog.MaskChooseDialog
import com.csgc.camera.widget.dialog.MaskEditDialog
import com.csgc.camera.widget.dialog.RemoveMaskLoadingDialog
import com.csgc.camera.widget.stickerView.BitmapStickerIcon
import com.csgc.camera.widget.stickerView.DeleteIconEvent
import com.csgc.camera.widget.stickerView.DrawableSticker
import com.csgc.camera.widget.stickerView.FlipHorizontallyEvent
import com.csgc.camera.widget.stickerView.Sticker
import com.csgc.camera.widget.stickerView.StickerView.OnStickerOperationListener
import com.csgc.camera.widget.stickerView.TextSticker
import com.csgc.camera.widget.stickerView.ZoomIconEvent
import com.cysd.spsyxj.R
import com.cysd.spsyxj.databinding.ActivityEditImageBinding
import com.drake.channel.receiveEvent
import com.drake.channel.sendEvent
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.ToastUtils
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.style.SelectMainStyle
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File


//https://github.com/Skykai521/StickerCamera
//https://github.com/wuapnjie/StickerView
class EditImageActivity :
    BaseBindingActivity<ActivityEditImageBinding>(ActivityEditImageBinding::inflate),
    IAdViewListener {

    companion object {

        private val KEY_IMAGE_URI = "image_uri"
        private val KEY_IMAGE_CACHE_PATH = "image_cache_path"
        private val KEY_IMAGE_REAL_PATH = "image_real_path"
        fun launch(context: Context, uri: String) {
            val intent = Intent(context, EditImageActivity::class.java)
            intent.putExtra(KEY_IMAGE_URI, uri)
            context.startActivity(intent)
        }

        fun launchPath(context: Context, path: String) {
            val intent = Intent(context, EditImageActivity::class.java)
            intent.putExtra(KEY_IMAGE_REAL_PATH, path)
            context.startActivity(intent)
        }

        //拍照不自动存储
        fun launchShare(context: Context, path: String) {
            val intent = Intent(context, EditImageActivity::class.java)
            intent.putExtra(KEY_IMAGE_CACHE_PATH, path)
            context.startActivity(intent)
        }
    }

    private val cachePath: String by lazy {
        intent.getStringExtra(KEY_IMAGE_CACHE_PATH) ?: ""
    }

    //高版本uri
    private var uri: Uri? = null
        get() {
            if (field == null) {
                intent.getStringExtra(KEY_IMAGE_URI)?.let {
                    field = Uri.parse(it)
                }
            }
            return field
        }

    private var realPath: String = ""
        get() {
            if (field.isEmpty()) {
                field = intent.getStringExtra(KEY_IMAGE_REAL_PATH) ?: ""
            }
            return field
        }
    private var uriRealPathName: String = ""

    //缓存无水印图片名字
    private val pathNameList: ArrayList<String> by lazy {
        ArrayList()
    }
    private var isShowLayout = true

    //加水印 去水印
    private val maskHandleDialog by lazy {
        val dialog = EditMaskDialog(this)
        dialog.listener = object : EditMaskDialog.OnItemClickListener {
            override fun onAddMask() {
                maskBottom.showDialog(supportFragmentManager, "mask")
            }

            override fun onRemoveMask() {
                removeLoadingDialog.showDialog()

            }
        }
        dialog
    }

    //去水印loading
    private val removeLoadingDialog: RemoveMaskLoadingDialog by lazy {
        val dialog = RemoveMaskLoadingDialog(this)
        dialog.listener = object : RemoveMaskLoadingDialog.OnLoadEndListener {
            override fun onLoadEnd() {
                val path = "${getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)}/$uriRealPathName"
                binding.ivImage.load(path) { allowHardware(false) }
            }
        }
        dialog
    }


    private val deleteDialog: CommonHandleTipsDialog by lazy {
        val dialog = CommonHandleTipsDialog(
            this,
            "提示",
            content = "是否永久删除该图片",
            leftTxt = "取消",
            rightTxt = "确定"
        )
        dialog.listener = object : CommonHandleTipsDialog.DialogActionListener {
            override fun sure(type: String) {
                //删除当前图片 有可能删除uri 有可能删除realpath
                deleteImg()
            }
        }
        dialog
    }

    /**
     * 删除图片
     */
    private fun deleteImg() {
        var deleteSuccess = false

        when {
            uri != null -> {
                // 通过 URI 删除图片
                deleteSuccess = uri?.deleteFromAlbum(this) ?: false
            }

            realPath.isNotEmpty() -> {
                // 通过文件路径删除图片
                val file = File(realPath)
                if (file.exists()) {
                    deleteSuccess = file.delete()
                }
            }

            cachePath.isNotEmpty() -> {
                // 通过缓存路径删除图片
                val file = File(cachePath)
                if (file.exists()) {
                    deleteSuccess = file.delete()
                }
            }
        }

        if (deleteSuccess) {
            ToastUtils.show("图片删除成功")
            sendEvent(DeleteAlbumEvents(true))
        }

        finish()
    }

    /**
     * 水印dialog
     */
    private val maskBottom: MaskChooseDialog by lazy {
        MaskChooseDialog()

    }

    //编辑水印
    private val editMaskDialog: MaskEditDialog by lazy {
        val dialog = MaskEditDialog(this)
        dialog
    }

    //水印图片编辑添加文字标注等
    private val editImageDialog: EditImageDialog by lazy {
        val dialog = EditImageDialog(this)
        dialog.listener = object : EditImageDialog.OnOptionListener {
            override fun onAddMask() {
                maskBottom.showDialog(supportFragmentManager, "mask")
            }

            override fun onAddTxt() {
                textDialog.show()
            }

            override fun onAddLabel() {
                labelDialog.show()
            }

            override fun onRemoveMask() {
                removeLoadingDialog.showDialog()
            }

            override fun onDismiss() {
//                binding.tvTitle.visibility = View.GONE
//                binding.tvComplete.visibility = View.GONE
            }
        }
        dialog
    }

    //标注
    private val labelDialog: EditImageLabelDialog by lazy {
        val dialog = EditImageLabelDialog(this)
        dialog.listListener = object : EditImageLabelDialog.OnLabelCheckListener {
            override fun onLabelCheck(style: Int,color: Int) {
                var drawableSticker  = DrawableSticker(
                    ContextCompat.getDrawable(
                        this@EditImageActivity,
                        R.drawable.img_label_arrow
                    )
                )
                if (style == 2) {
                     drawableSticker = DrawableSticker(
                        ContextCompat.getDrawable(
                            this@EditImageActivity,
                            R.drawable.img_label_rect
                        )
                    )
                } else if (style == 3) {
                     drawableSticker = DrawableSticker(
                        ContextCompat.getDrawable(
                            this@EditImageActivity,
                            R.drawable.img_label_circle
                        )
                    )
                }
                drawableSticker.setColor(color)
                binding.stickerView.addSticker(drawableSticker)
            }
        }
        dialog
    }

    private val bubbleDrawable: Drawable? by lazy {
        ContextCompat.getDrawable(this, R.drawable.shape_blue_bg_radius15)
    }

    private val markDrawable: Drawable? by lazy {
         ContextCompat.getDrawable(this, R.drawable.ic_marked_text)

    }

    private val checkInDrawable: Drawable? by lazy {
          ContextCompat.getDrawable(this, R.drawable.ic_mark_attendance)
    }

    private val whiteBgInDrawable: Drawable? by lazy {
        ContextCompat.getDrawable(this, R.drawable.shape_rc_white_bg_radius10_wh)
    }



    private val textDialog: EditImageTxtDialog by lazy {
        val dialog = EditImageTxtDialog(this)
        dialog.listener = object : EditImageTxtDialog.OnLabelCheckListener {
            override fun onCheck(style: Int, color: Int, text: String) {
                when (style) {
                    1 -> {
                        binding.stickerView.addSticker(
                            TextSticker(this@EditImageActivity)
                                .setText(text)
                                .setTextColor(color)
                                .setMaxTextSize(16f)
                                .resizeText()
                                .setTextAlign(Layout.Alignment.ALIGN_CENTER)
                        )
                    }

                    2 -> {
                        // 添加空值检查
                        bubbleDrawable?.let { drawable ->
                            binding.stickerView.addSticker(
                                TextSticker(this@EditImageActivity)
                                    .setText(text)
                                    .setTextColor(color)
                                    .setMaxTextSize(16f)
                                    .setDrawable(drawable)
                                    .resizeText()
                                    .setTextAlign(Layout.Alignment.ALIGN_CENTER),
                                Sticker.Position.CENTER
                            )
                        }
                    }

                    3 -> {
                        // 同样添加空值检查
                        markDrawable?.let { drawable ->
                            binding.stickerView.addSticker(
                                TextSticker(this@EditImageActivity)
                                    .setText(text)
                                    .setTextColor(color)
                                    .setMaxTextSize(16f)
                                    .setLeftIcon(drawable!!)
                                    .setDrawable(whiteBgInDrawable!!)
                                    .resizeText()
                                    .setTextAlign(Layout.Alignment.ALIGN_CENTER),
                                Sticker.Position.CENTER
                            )
                        }
                    }

                    4 ->{
                        // 同样添加空值检查
                        checkInDrawable?.let { drawable ->
                            binding.stickerView.addSticker(
                                TextSticker(this@EditImageActivity)
                                    .setText(text)
                                    .setTextColor(color)
                                    .setMaxTextSize(16f)
                                    .setLeftIcon(drawable!!)
                                    .setDrawable(whiteBgInDrawable!!)
                                    .resizeText()
                                    .setTextAlign(Layout.Alignment.ALIGN_CENTER),
                                Sticker.Position.CENTER
                            )
                        }
                    }
                }
            }
        }
        dialog
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        immersionBar {
            statusBarDarkFont(false) // 指定导航栏背景颜色
            navigationBarColor(R.color.white)
            autoDarkModeEnable(true, 0.2f)
            statusBarDarkFont(false)
            hideBar(BarHide.FLAG_HIDE_BAR)
        }
        showDoubleChaPin()
        if (cachePath.isNotEmpty()) {
            binding.ivImage.load(cachePath) { allowHardware(false) }
//            binding.tvComplete.visibility = View.GONE
        } else if (realPath.isNotEmpty()) {
            binding.ivImage.load(realPath) {
                allowHardware(false)
            }
        } else {
            binding.ivImage.load(uri) {
                allowHardware(false)
            }
        }

        initStickView()
        initEvents()


        loadCacheNoMaskImage()
        showMaskImage()
    }

    private fun showMaskImage() {
        if (cachePath.isEmpty()) {

            if (realPath.isEmpty()) {
                uriRealPathName = getFileName(GetPathFromUri.getPath(this, uri)) ?: ""
            } else {
                uriRealPathName = getFileName(realPath) ?: ""
            }


            val bitmap: Bitmap? = if (realPath.isEmpty()) {
                BitmapFactory.decodeFile(GetPathFromUri.getPath(this, uri))
            } else {
                BitmapFactory.decodeFile(realPath)
            }

            //先清空ivimage的图层
            if (bitmap == null) {
                if (realPath.isEmpty()) {
                    binding.ivImage.load(uri) {
                        allowHardware(false)
                    }
                } else {
                    binding.ivImage.load(realPath) {
                        allowHardware(false)
                    }
                }
                return
            }
            val btwidth = bitmap.width
            val btheight = bitmap.height

            var loadWidth = 0
            var loadHeight = 0
            if (btwidth > ViewUtils.getScreenWidth(this)) {
                loadWidth = ViewUtils.getScreenWidth(this)
                loadHeight =
                    btwidth * ViewUtils.getScreenHeight(this) / ViewUtils.getScreenWidth(this)

                if (realPath.isEmpty()) {
                    binding.ivImage.load(uri) {
                        size(loadWidth, loadHeight)
                        allowHardware(false)
                    }
                } else {
                    binding.ivImage.load(realPath) {
                        size(loadWidth, loadHeight)
                        allowHardware(false)
                    }
                }

            } else {
                if (realPath.isEmpty()) {
                    binding.ivImage.load(uri) {
                        size(btwidth, btheight)
                        allowHardware(false)
                    }
                } else {
                    binding.ivImage.load(realPath) {
                        size(btwidth, btheight)
                        allowHardware(false)
                    }
                }
            }


        } else {
            uriRealPathName = getFileName(cachePath) ?: ""
            val bitmap: Bitmap? = BitmapFactory.decodeFile(cachePath)

            if (bitmap == null) {
                binding.ivImage.load(cachePath) {
                    allowHardware(false)
                }
                return
            }

            val btwidth = bitmap.width
            val btheight = bitmap.height

            var loadWidth = 0
            var loadHeight = 0
            if (btwidth > ViewUtils.getScreenWidth(this)) {
                loadWidth = ViewUtils.getScreenWidth(this)
                loadHeight =
                    btwidth * ViewUtils.getScreenHeight(this) / ViewUtils.getScreenWidth(this)
                binding.ivImage.load(cachePath) {
                    size(loadWidth, loadHeight)
                    allowHardware(false)
                }
            }/*else{

                loadHeight = btheight
                loadWidth = ViewUtils.getScreenWidth(this)*loadHeight/ViewUtils.getScreenHeight(this)

            }*/
        }
    }

    private var currentMask: CustomMaskHandle? = null
    private var maskType = 0
    private var maskId = 0
    private fun showMaskView() {

        binding.layoutMaskContainer.removeAllViews()
        val maskView = MaskConfig.getMaskView(this, maskType, maskId)
        currentMask = maskView
        binding.layoutMaskContainer.addView(maskView)

    }

    private fun initEvents() {
        receiveEvent<ChangeMaskEvent> {
            maskType = it.type
            maskId = it.id
            showMaskView()
        }

        receiveEvent<CustomMaskEvent> {
            currentMask?.onAddCustom()
        }

        receiveEvent<ChangeCustomMaskStatusEvent> {
            currentMask?.changeCustomStatus()
        }

        receiveEvent<showMaskEditDialogEvent> {
            maskBottom.dismiss()
            editMaskDialog.initData(maskType, maskId)
            editMaskDialog.show(maskType, maskId)
        }

        binding.ivCloseBack.clickWithTrigger {
            if (cachePath.isNotEmpty()) {
                val file = File(cachePath)
                if (file.exists()) {
                    file.delete()
                    val cacheFile =
                        File("${getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)}/${file.name}")
                    if (cacheFile.exists()) {
                        cacheFile.delete()
                    }
                }

            }
            finish()
        }

        binding.ivImage.clickWithTrigger {

            if (isShowLayout) {
                isShowLayout = false

                changeBottomStatus(false)
                changeTopStatus(false)
            } else {
                isShowLayout = true
                changeBottomStatus(true)
                changeTopStatus(true)
            }
        }

        binding.tvToAlbum.clickWithTrigger {
            val picStyle = PictureSelectorStyle()
            val selectStyle = SelectMainStyle()
            selectStyle.selectText = "确定"

            picStyle.selectMainStyle = selectStyle
            PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(CoilEngine())
                .setLanguage(LanguageConfig.CHINESE)
                .setSelectionMode(SelectModeConfig.SINGLE)
                .setImageSpanCount(3)
                .isGif(false)
                .isBmp(false)
                .isWebp(false)
                .setSkipCropMimeType()
                .isDisplayCamera(false)
                .isPreviewImage(false)
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .setSelectorUIStyle(picStyle)
                .forResult(object : OnResultCallbackListener<LocalMedia?> {
                    override fun onResult(result: ArrayList<LocalMedia?>) {
                        result[0]?.let {
                            if (it.path.startsWith("content://")) {
                                uri = Uri.parse(it.path)
                            } else {
                                realPath = it.path
                            }
                            loadCacheNoMaskImage()
                            showMaskImage()
                        }
                    }

                    override fun onCancel() {

                    }
                })
        }
        binding.tvShareAll.clickWithTrigger {
            shareImage()
        }
        binding.tvDeleteImg.clickWithTrigger {
            //删除当前图片
            deleteDialog?.showDialog()
        }
        binding.tvImageEdit.clickWithTrigger {
            binding.tvComplete.visibility = View.VISIBLE
            binding.tvTitle.visibility = View.VISIBLE
            editImageDialog.show(pathNameList.contains(uriRealPathName))
        }

        binding.layoutMaskContainer.clickWithTrigger {
            editMaskDialog.initData(maskType, maskId)
            editMaskDialog.show(maskType, maskId)
        }

        binding.tvComplete.clickWithTrigger {
            binding.tvComplete.visibility = View.GONE
            binding.tvTitle.visibility = View.GONE
            binding.stickerView.showIcons = false
            binding.stickerView.invalidate()

            //1.判断是否有水印生成水印
            var maskBitmap: Bitmap? = null
            if (binding.layoutMaskContainer.childCount > 0) {
                maskBitmap = ViewUnit.captureView(binding.layoutMaskContainer)
            }

            var name = "today_puzzle_${System.currentTimeMillis()}.png"
            /*if (cachePath.isNotEmpty()){
                name = getFileName(cachePath)?:"today_puzzle_${System.currentTimeMillis()}.png"
            }*/

            //没有水印图片
            val bitmap = ViewUnit.captureView(binding.stickerView)
            if (maskBitmap == null) {
                lifecycleScope.launch(Dispatchers.IO) {

                    val uri = bitmap?.saveToAlbum(this@EditImageActivity, name, quality = 100)
                    lifecycleScope.launch(Dispatchers.Main) {
                        if (uri != null) {
                            ToastUtils.show("已保存至相册！")
                            finish()
                        }

                    }

                }
            } else {
                //有水印图片----水印图片位置
                val finalBitmap = ImageUtil.createWaterMaskLeftBottom(bitmap, maskBitmap, -5, 15)
                lifecycleScope.launch(Dispatchers.IO) {

                    //无水印存储到缓存
                    bitmap?.let {
                        getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)?.let { it1 ->
                            CommonUtils.saveBitmapToCache(
                                bitmap,
                                it1,
                                name
                            )
                        }
                    }


                    val uri = finalBitmap?.saveToAlbum(this@EditImageActivity, name, quality = 100)
                    lifecycleScope.launch(Dispatchers.Main) {
                        if (uri != null) {
                            ToastUtils.show("已保存至相册！")
                            finish()
                        }

                    }

                }
            }
        }


    }


    private fun changeBottomStatus(status: Boolean) {
        val bottomAnim = binding.layoutBottom.animate()
        bottomAnim.duration = 500
        bottomAnim.interpolator = AccelerateDecelerateInterpolator()
        if (status) {
            bottomAnim.translationY(0f)
        } else {
            bottomAnim.translationY(86.dp.toFloat())
        }

        bottomAnim.start()

    }

    private fun changeTopStatus(status: Boolean) {
        val bottomAnim = binding.layoutTop.animate()
        bottomAnim.duration = 500
        bottomAnim.interpolator = AccelerateDecelerateInterpolator()
        if (status) {
            bottomAnim.translationY(0f)
        } else {
            bottomAnim.translationY(-44.dp.toFloat())
        }

        bottomAnim.start()

    }


    fun shareSingleImageToWX() {
        if (!WXWrapper.instance.wxApi.isWXAppInstalled) {
            ToastUtils.show("您尚未安装微信")
            return
        }
        val intent = Intent()
        //发送图片给好友
        val componentName = ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI")
        intent.component = componentName
        intent.action = Intent.ACTION_SEND
        intent.type = "image/*"
        if (cachePath.isNotEmpty()) {
            intent.putExtra(Intent.EXTRA_STREAM, FileUtils.getUriForFile(this, File(cachePath)))
        } else if (realPath.isNotEmpty()) {
            intent.putExtra(Intent.EXTRA_STREAM, FileUtils.getUriForFile(this, File(realPath)))
        } else {
            intent.putExtra(Intent.EXTRA_STREAM, uri)
        }

        startActivity(intent)

    }

    fun shareToFriend() {
        val intent = Intent()

        val componentName =
            ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
        intent.component = componentName
        intent.action = Intent.ACTION_SEND
        intent.type = "image/*"
        intent.putExtra(Intent.EXTRA_STREAM, uri)
        startActivity(intent);

    }


    private fun shareImage() {
        val intent = Intent()
        intent.action = Intent.ACTION_SEND
        intent.type = "image/*"
        if (cachePath.isNotEmpty()) {
            intent.putExtra(Intent.EXTRA_STREAM, FileUtils.getUriForFile(this, File(cachePath)))
        } else if (realPath.isNotEmpty()) {
            intent.putExtra(Intent.EXTRA_STREAM, FileUtils.getUriForFile(this, File(realPath)))
        } else {
            intent.putExtra(Intent.EXTRA_STREAM, uri)
        }
        startActivity(Intent.createChooser(intent, "title"))
    }


    private fun initStickView() {
        binding.stickerView.setBackgroundColor(Color.WHITE)
        binding.stickerView.isLocked = false
        binding.stickerView.isConstrained = true

        val deleteIcon = BitmapStickerIcon(
            ContextCompat.getDrawable(
                this,
                R.drawable.sticker_ic_close_white_18dp
            ),
            BitmapStickerIcon.LEFT_TOP
        )
        deleteIcon.iconEvent = DeleteIconEvent()

        val zoomIcon = BitmapStickerIcon(
            ContextCompat.getDrawable(
                this,
                R.drawable.sticker_ic_scale_white_18dp
            ),
            BitmapStickerIcon.RIGHT_BOTOM
        )
        zoomIcon.iconEvent = ZoomIconEvent()

        val flipIcon = BitmapStickerIcon(
            ContextCompat.getDrawable(
                this,
                R.drawable.sticker_ic_flip_white_18dp
            ),
            BitmapStickerIcon.RIGHT_TOP
        )
        flipIcon.iconEvent = FlipHorizontallyEvent()


        binding.stickerView.icons = listOf(deleteIcon, zoomIcon);

        binding.stickerView.onStickerOperationListener = object : OnStickerOperationListener {
            override fun onStickerAdded(sticker: Sticker) {

            }

            override fun onStickerClicked(sticker: Sticker) {
                //                binding.stickerView.showIcons = false
                //                binding.stickerView.invalidate()
            }

            override fun onStickerDeleted(sticker: Sticker) {

            }

            override fun onStickerDragFinished(sticker: Sticker) {
            }

            override fun onStickerTouchedDown(sticker: Sticker) {
            }

            override fun onStickerZoomFinished(sticker: Sticker) {
            }

            override fun onStickerFlipped(sticker: Sticker) {
            }

            override fun onStickerDoubleTapped(sticker: Sticker) {
            }
        }

    }

    //获取缓存中无水印的图片
    private fun loadCacheNoMaskImage() {

        getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)?.listFiles()?.forEach { file ->
            file?.let {
//                XLog.e("====cache${it.path}")
//                XLog.e("====cache${it.name}")
                pathNameList.add(it.name)
            }
        }

    }

    private fun getFileName(pathandname: String): String? {
        if (pathandname.isEmpty()) {
            return null
        }
        val start = pathandname.lastIndexOf("/")
        val end = pathandname.lastIndexOf(".")
        return if (start != -1 && end != -1) {
            pathandname.substring(start + 1, pathandname.length)
        } else {
            null
        }
    }

    override fun onBackPressed() {
        if (cachePath.isNotEmpty()) {
            val file = File(cachePath)
            if (file.exists()) {
                file.delete()
                val cacheFile =
                    File("${getExternalFilesDir(Constants.NO_MASK_CACHE_IMAGE)}/${file.name}")
                if (cacheFile.exists()) {
                    cacheFile.delete()
                }
            }

        }
        super.onBackPressed()
    }

    /* private suspend fun loadBitmap():Bitmap{
        val request = ImageRequest.Builder(this)
            .data("content://media/external/images/media/119317")
            .build()
        val result = (imageLoader.execute(request) as SuccessResult).drawable
        XLog.e("=====bitmap${result.intrinsicWidth}")
        XLog.e("=====bitmap${result.intrinsicHeight}")
        val bitmap = (result as BitmapDrawable).bitmap
        XLog.e("=====bitmap${bitmap.width}")
        XLog.e("=====bitmap${bitmap.height}")
        XLog.e("=====bitmapview${ViewUtils.getScreenWidth(this)}")
        XLog.e("=====bitmapview${ViewUtils.getScreenHeight(this)}")
       return bitmap
    }*/


    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {

    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {

    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {

    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }

    //统一双插屏无需加位置
    fun showDoubleChaPin() {
        AdManager.loadTwoChapinSimultaneously(
            this,
            666,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {

                }
            })
    }
}